package cn.wolfcode.crm.util;


import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;

public class EmployeeRealm extends AuthorizingRealm {
    @Setter
    private IEmployeeService employeeService;

    public String getName(){
        return "EmployeeRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        Employee user = (Employee) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //查询数据库获取角色和权限信息
        if(user.isAdmin()){
            info.addStringPermission("*:*");
        }else{
            info.addRoles(Arrays.asList("hr"));
            info.addStringPermissions(Arrays.asList("employee:index","employee:list"));
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        Employee employee = employeeService.checkName((String) token.getPrincipal());
        if(employee==null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee,employee.getPassword(), this.getName());

        return info;
    }
}
